package com.base.common.mybatis.handler;

import com.base.api.Message;
import com.base.common.util.FastJsonConvertUtil;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.springframework.util.StringUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class MessageJsonTypeHandler extends BaseTypeHandler<Message> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, Message message, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i,FastJsonConvertUtil.getBeanToJson(message));
    }

    @Override
    public Message getNullableResult(ResultSet resultSet, String columnName) throws SQLException {
        String value = resultSet.getString(columnName);
        if (StringUtils.isEmpty(value)) {
            return null;
        }
        return FastJsonConvertUtil.getJsonToBean(value, Message.class);
    }

    @Override
    public Message getNullableResult(ResultSet resultSet, int i) throws SQLException {
        String value = resultSet.getString(i);
        if (!StringUtils.isEmpty(value)) {
            return null;
        }
        return FastJsonConvertUtil.getJsonToBean(value, Message.class);
    }

    @Override
    public Message getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        String value = callableStatement.getString(i);
        if (!StringUtils.isEmpty(value)) {
            return null;
        }
        return FastJsonConvertUtil.getJsonToBean(value, Message.class);
    }
}
